<template>
    <rx-dialog @handOk="handOk" @cancel="cancel" :oktext="$ti18('rxForm.saveBtn','保存')" :canceltext="$ti18('rxForm.cancelBtn','取消')" order="top" btnalign="right">
        <div slot="toolbar">
            <a-button type="primary" @click="openSealDialog">{{i18n('list.btnOpenSeal','选择盖章')}}</a-button>
            <a-button type="primary" @click="setPagingSeal">{{i18n('list.btnPagingSeal','骑缝章配置')}}</a-button>
            <a-button type="primary" @click="openSignDialog">{{i18n('list.btnOpenSign','选择签名')}}</a-button>
            <a-button type="primary" @click="insertDate">{{i18n('list.btnInsertDate','插入日期')}}</a-button>
        </div>
        <rx-layout>
            <div slot="center" style="height: calc( 100% - 40px );width:100%;">
                <iframe ref="rxIframe" :src="getUrl()" style="width:100%;height:100%;"></iframe>
            </div>
        </rx-layout>
    </rx-dialog>
</template>

<script>

let baseUrl = process.env.VUE_APP_ADMIN_FRONT;
import {Util,TokenUtil} from "@lowcode/jpaas-common-lib"
import SelectSealDialog from "./PdfDialog/SelectSealDialog";
import SelectSignDialog from "./PdfDialog/SelectSignDialog";
import PagingSealDialog from "./PdfDialog/PagingSealDialog";
import InsertDateDialog from "./PdfDialog/InsertDateDialog";
import FormStampApi from "@/api/form/core/formStamp";
export default {
    name: "pdfSealSignature",
    props:{
        layerid: String,
        lydata: Object,
        destroy: Function,
        file: Object,
    },
    mounted() {
        let self = this;
        window.addEventListener('message', function (event) {
            //此处执行事件
            if (event && event.data) {
                if (event.data.eventName == "openDialog") {//打开印章；
                 //   self.thr(self.openSealDialog,500).call(self)
                    if (!self.open) {//防止重复触发
                        self.openSealDialog(event.data)
                    }
                }
            }
        })
    },
    data() {
        return {
            open:false,
            //骑缝章配置
            pagingSeal:"",
            pkId:""
        }
    },
    created() {
        this.getPdfPositions();
    },
    methods: {
        i18n(name,text,key){
            return this.$ti18(name,text,"PdfSealSignature",key);
        },
        thr(fn,t) {
            let time = null
            return function () {
                clearTimeout(time)
                time = setTimeout(function () {
                    fn()
                }, t)
            }
        },
        getData(){
            let _iframe = this.$refs.rxIframe.contentWindow;
            let {sealPosition} = _iframe.PDFViewerApplication;
            return sealPosition;
        },
        openSealDialog(eventData) {
            this.open = true ;
            let self = this ;
            let config = {
                curVm: this,
                widthHeight: ['1000px', '600px'],
                component: SelectSealDialog,
                cancel:()=>{ self.open = false }
            }
            Util.open(config, function (action, data) {
                if(action !='ok'){ return }
                let _iframe = self.$refs.rxIframe.contentWindow;
                let url = self.getImagePath(data.fileId);
                data.type="stamp";
                let _obj = {
                    ...data,
                    url
                }
                let page = _iframe.PDFViewerApplication.page ;
                _iframe.PDFViewerApplication.SetPosition(_obj,page);
                self.open = false ;
            })
        },
        openSignDialog(eventData){
            let self = this ;
            let config = {
                curVm: this,
                widthHeight: ['1000px', '600px'],
                component: SelectSignDialog,
            }
            Util.open(config, function (action, data) {
                if(action !='ok'){ return }
                let _iframe = self.$refs.rxIframe.contentWindow;
                let url = self.getImagePath(data.fileId);
                data.type="sign";
                let _obj = {
                    ...data,
                    url
                }
                let page = _iframe.PDFViewerApplication.page ;
                _iframe.PDFViewerApplication.SetPosition(_obj,page);
            })
        },
        setPagingSeal(){
            let self = this ;
            let config = {
                curVm: this,
                title:self.i18n('list.setPagingSealTitle','骑缝章配置'),
                widthHeight: ['700px', '600px'],
                component: PagingSealDialog,
                data:{
                    pagingSeal:self.pagingSeal
                }
            }
            Util.open(config, function (action, data) {
                if(action !='ok'){ return }
                self.pagingSeal=data;
            })
        },
        insertDate(eventData){
            let self = this ;
            let config = {
                curVm: this,
                title:self.i18n('list.setDateTitle','日期配置'),
                widthHeight: ['700px', '420px'],
                component: InsertDateDialog,
                data:{
                    dateConfig:{}
                }
            }
            Util.open(config, function (action, data) {
                if(action !='ok'){ return }
                let _iframe = self.$refs.rxIframe.contentWindow;
                let page = _iframe.PDFViewerApplication.page ;
                _iframe.PDFViewerApplication.SetPosition(data,page);
            })
        },
        getImagePath(fileId) {
            let accessToken = TokenUtil.getToken();
            let time=new Date().getTime();
            fileId=Util.encryptWord(fileId);
            var isScale=Util.encryptWord(false);
            let url = `/api/api-system/system/core/sysFile/previewImg?fileId=${fileId}&accessToken=${accessToken}&time=${time}&isScale=${isScale}` ;
            return url;
        },
        getUrl() {
            let url = baseUrl + "/cdn/pdfjs/web/viewer.html?file=" + this.getFilePath();
            return url;
        },
        getFilePath(){
            if(!this.file || !this.file.fileId){
                return ""
            }
            let token = TokenUtil.getToken();
            var fileId=Util.encryptWord(this.file.fileId);
            return "/api/api-system/system/core/sysFile/previewFile?fileId=" + fileId + "&accessToken=" + token;
        },
        handOk(vm){
            let positions=this.getData();
            if(this.pagingSeal){
                positions["pagingSeal"]=this.pagingSeal;
            }
            let obj={
                positions:positions,
                pdfDto:this.file,
                pkId:this.pkId
            }
            FormStampApi.savePdfPositions(obj).then(res=>{
                if(res.success){
                    Util.closeWindow(this, "ok");
                }else {
                    vm.loading=false;
                }
            }).catch(err=>{
                vm.loading=false;
            });
        },
        cancel(){
            Util.closeWindow(this,"cancel");
        },
        //回填
        getPdfPositions(){
            if(!this.file || !this.file.fileId){
               return;
            }
            let self= this ;
            FormStampApi.getPdfPositions(this.file.fileId).then(res=>{
                if(res.success){
                    if(res.data && res.data.length > 0){
                        let config = res.data[0].config ;
                        self.pkId=res.data[0].pkId;
                        let _config = JSON.parse(config);
                        for(let key in _config){
                            for (let item of _config[key]){
                                let url = self.getImagePath(item.fileId);
                                item['url'] = url
                            }
                        }

                        let _iframe = self.$refs.rxIframe.contentWindow;
                        _iframe.onload = function (){
                            let time = setInterval(function () {
                                let isInitialViewSet =  _iframe.PDFViewerApplication.isInitialViewSet ;
                                if(isInitialViewSet){
                                    try {
                                        _iframe.PDFViewerApplication.createdDiv(_config);
                                        clearInterval(time)
                                    }catch (e){
                                        clearInterval(time)
                                    }
                                }
                            },500)

                        }
                    }
                }
            });
        }
    }
}
</script>

<style scoped>

</style>
